<?php
namespace app\wechat\controller;

use app\wechat\controller\Common;

use think\Request;
use think\db;

class CallbackController
{
    
    public function index(){
        $code = Request::instance()->get('code'); 
        if($code){
            $common = new Common();
            $param = ['query' => ['access_token' => $common->getAccessToken(), 'code' => $code] ];
            $user = $common->wechatHttp('/user/getuserinfo', $param);
            $user = json_decode($user,TRUE);
            $_SESSION['wechat_user'] = $user;
            //$_SESSION['wechat_user'] = ['UserId' => 'swjtest', 'DeviceId' => 'b814dcc5-5176-4668-9f5e-e2db09c51d15', 'errcode' => 0 ,'errmsg' => 'ok' ];
            $userid = $user['UserId'];
            //$userid = 'swjtest';
            
            $userQuery = Db::name("member");
            $result = $userQuery->where('openid', $userid)->find();
            session('user',$result);
            
            $targetUrl = empty($_SESSION['target_url']) ? '/' : $_SESSION['target_url'];
            
            
            header('location:'. $targetUrl); // 跳转到 user/profile
        }
    }

}